<?php

namespace app\site\controller;

use app\common\service\WebSocket;
use app\common\model\AppMember;
use think\admin\Controller;
use think\admin\extend\ExcelExtend;
use think\facade\Db;
use Exception;

/**
 * 捐款管理
 * Class Member
 * @package app\site\controller
 */
class Member extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    public $table = 'AppMember';

    /**
     * 用户管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $total['money'] = Db::name($this->table)->where('status', 1)->sum('money');
        $total['member'] = Db::name($this->table)->where('status', 1)->count();
        $total['page_money'] = (new AppMember())->moneyCount();
        $this->assign('total', $total);
        $this->title = '捐款记录';
        $where = [];
        $condition = $this->request->get('condition') ?? 99;
        switch ($condition) {
            case 0:
                $where[] = ['money', '<', 1];
                break;
            case 1:
                $where[] = ['money', '<', 10];
                break;
            case 2:
                $where[] = ['money', '>', 10000];
                break;
        }
        $query = $this->_query($this->table)->where($where)->like('phone,realname')->equal('id,status');
        $query->dateBetween('create_at')->order('id desc')->page();
    }

    /**
     * 修改用户状态
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function state()
    {
        $this->_applyFormToken();
        $this->_save($this->table, ['status' => intval(input('status'))]);
    }

    /**
     * 更新结果
     * @param $res
     * @throws \Exception
     */
    protected function _save_result($res)
    {
        if ('state' == $this->request->action()) {
            try {
                WebSocket::sendToAll('update');
            } catch (Exception $e) {
                sysoplog('站点管理', 'WebSocket连接失败' . $e->getMessage());
            }
        }
    }

    /**
     * 导出报表
     * @auth true  # 表示需要验证权限
     * @login true # 需要强制登录可访问
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function export()
    {
        set_time_limit(0);
        $tableName = sysconf('site_name') . date('Y-m-d h:i') . '数据导出.csv';
        $get = $this->request->get();
        $where = [];
        $condition = $get['condition'] ?? 99;
        switch ($condition) {
            case 0:
                $where[] = ['money', '<', 1];
                break;
            case 1:
                $where[] = ['money', '<', 10];
                break;
            case 2:
                $where[] = ['money', '>', 10000];
                break;
        }
        foreach (['phone', 'realname'] as $field) {
            if (isset($get[$field]) && '' !== $get[$field]) {
                $where[] = [$field, 'like', "%{$get[$field]}%"];
            }
        }
        foreach (['id', 'status'] as $field) {
            if (isset($get[$field]) && '' !== $get[$field]) {
                $where[] = [$field, '=', $get[$field]];
            }
        }
        // 订单时间过滤
        foreach (['create_at'] as $field) {
            if (isset($get[$field]) && '' !== $get[$field]) {
                list($start, $end) = explode(' - ', $get[$field]);
                $where[] = [$field, 'between time', ["{$start} 00:00:00", "{$end} 23:59:59"]];
            }
        }
        $cells = [
            'id'        => 'ID',
            'realname'  => '捐款人',
            'phone'     => '联系方式',
            'money'     => '捐款金额',
            'status'    => '显示状态',
            'create_at' => '提交时间',
        ];
        $data = Db::name($this->table)->field(array_keys($cells))->where($where)->order('id desc')->select()->toArray();
        $statusArr = ['隐藏', '显示'];
        foreach ($data as &$vo) {
            $vo['status'] = $statusArr[$vo['status']] ?? '--';
        }
        ExcelExtend::header($tableName, array_values($cells));
        ExcelExtend::body($data, array_keys($cells));
    }
}